home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / inspect.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  37KB  |  1,016 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Get useful information from live Python objects.
  5.  
  6. This module encapsulates the interface provided by the internal special
  7. attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
  8. It also provides some help for examining source code and class layout.
  9.  
  10. Here are some of the useful functions provided by this module:
  11.  
  12.     ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
  13.         isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
  14.         isroutine() - check object types
  15.     getmembers() - get members of an object that satisfy a given condition
  16.  
  17.     getfile(), getsourcefile(), getsource() - find an object's source code
  18.     getdoc(), getcomments() - get documentation on an object
  19.     getmodule() - determine the module that an object came from
  20.     getclasstree() - arrange classes so as to represent their hierarchy
  21.  
  22.     getargspec(), getargvalues() - get info about function arguments
  23.     formatargspec(), formatargvalues() - format an argument spec
  24.     getouterframes(), getinnerframes() - get info about frames
  25.     currentframe() - get the current stack frame
  26.     stack(), trace() - get info about frames on the stack or in a traceback
  27. """
  28. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  29. __date__ = '1 Jan 2001'
  30. import sys
  31. import os
  32. import types
  33. import string
  34. import re
  35. import dis
  36. import imp
  37. import tokenize
  38. import linecache
  39. from operator import attrgetter
  40. from collections import namedtuple
  41. (CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS) = (1, 2, 4, 8)
  42. (CO_NESTED, CO_GENERATOR, CO_NOFREE) = (16, 32, 64)
  43. TPFLAGS_IS_ABSTRACT = 1048576
  44.  
  45. def ismodule(object):
  46.     '''Return true if the object is a module.
  47.  
  48.     Module objects provide these attributes:
  49.         __doc__         documentation string
  50.         __file__        filename (missing for built-in modules)'''
  51.     return isinstance(object, types.ModuleType)
  52.  
  53.  
  54. def isclass(object):
  55.     '''Return true if the object is a class.
  56.  
  57.     Class objects provide these attributes:
  58.         __doc__         documentation string
  59.         __module__      name of module in which this class was defined'''
  60.     if not isinstance(object, types.ClassType):
  61.         pass
  62.     return hasattr(object, '__bases__')
  63.  
  64.  
  65. def ismethod(object):
  66.     '''Return true if the object is an instance method.
  67.  
  68.     Instance method objects provide these attributes:
  69.         __doc__         documentation string
  70.         __name__        name with which this method was defined
  71.         im_class        class object in which this method belongs
  72.         im_func         function object containing implementation of method
  73.         im_self         instance to which this method is bound, or None'''
  74.     return isinstance(object, types.MethodType)
  75.  
  76.  
  77. def ismethoddescriptor(object):
  78.     '''Return true if the object is a method descriptor.
  79.  
  80.     But not if ismethod() or isclass() or isfunction() are true.
  81.  
  82.     This is new in Python 2.2, and, for example, is true of int.__add__.
  83.     An object passing this test has a __get__ attribute but not a __set__
  84.     attribute, but beyond that the set of attributes varies.  __name__ is
  85.     usually sensible, and __doc__ often is.
  86.  
  87.     Methods implemented via descriptors that also pass one of the other
  88.     tests return false from the ismethoddescriptor() test, simply because
  89.     the other tests promise more -- you can, e.g., count on having the
  90.     im_func attribute (etc) when an object passes ismethod().'''
  91.     if hasattr(object, '__get__') and not hasattr(object, '__set__') and not ismethod(object) and not isfunction(object):
  92.         pass
  93.     return not isclass(object)
  94.  
  95.  
  96. def isdatadescriptor(object):
  97.     '''Return true if the object is a data descriptor.
  98.  
  99.     Data descriptors have both a __get__ and a __set__ attribute.  Examples are
  100.     properties (defined in Python) and getsets and members (defined in C).
  101.     Typically, data descriptors will also have __name__ and __doc__ attributes
  102.     (properties, getsets, and members have both of these attributes), but this
  103.     is not guaranteed.'''
  104.     if hasattr(object, '__set__'):
  105.         pass
  106.     return hasattr(object, '__get__')
  107.  
  108. if hasattr(types, 'MemberDescriptorType'):
  109.     
  110.     def ismemberdescriptor(object):
  111.         '''Return true if the object is a member descriptor.
  112.  
  113.         Member descriptors are specialized descriptors defined in extension
  114.         modules.'''
  115.         return isinstance(object, types.MemberDescriptorType)
  116.  
  117. else:
  118.     
  119.     def ismemberdescriptor(object):
  120.         '''Return true if the object is a member descriptor.
  121.  
  122.         Member descriptors are specialized descriptors defined in extension
  123.         modules.'''
  124.         return False
  125.  
  126. if hasattr(types, 'GetSetDescriptorType'):
  127.     
  128.     def isgetsetdescriptor(object):
  129.         '''Return true if the object is a getset descriptor.
  130.  
  131.         getset descriptors are specialized descriptors defined in extension
  132.         modules.'''
  133.         return isinstance(object, types.GetSetDescriptorType)
  134.  
  135. else:
  136.     
  137.     def isgetsetdescriptor(object):
  138.         '''Return true if the object is a getset descriptor.
  139.  
  140.         getset descriptors are specialized descriptors defined in extension
  141.         modules.'''
  142.         return False
  143.  
  144.  
  145. def isfunction(object):
  146.     '''Return true if the object is a user-defined function.
  147.  
  148.     Function objects provide these attributes:
  149.         __doc__         documentation string
  150.         __name__        name with which this function was defined
  151.         func_code       code object containing compiled function bytecode
  152.         func_defaults   tuple of any default values for arguments
  153.         func_doc        (same as __doc__)
  154.         func_globals    global namespace in which this function was defined
  155.         func_name       (same as __name__)'''
  156.     return isinstance(object, types.FunctionType)
  157.  
  158.  
  159. def isgeneratorfunction(object):
  160.     '''Return true if the object is a user-defined generator function.
  161.  
  162.     Generator function objects provides same attributes as functions.
  163.  
  164.     See isfunction.__doc__ for attributes listing.'''
  165.     if isfunction(object) or ismethod(object):
  166.         pass
  167.     return bool(object.func_code.co_flags & CO_GENERATOR)
  168.  
  169.  
  170. def isgenerator(object):
  171.     '''Return true if the object is a generator.
  172.  
  173.     Generator objects provide these attributes:
  174.         __iter__        defined to support interation over container
  175.         close           raises a new GeneratorExit exception inside the
  176.                         generator to terminate the iteration
  177.         gi_code         code object
  178.         gi_frame        frame object or possibly None once the generator has
  179.                         been exhausted
  180.         gi_running      set to 1 when generator is executing, 0 otherwise
  181.         next            return the next item from the container
  182.         send            resumes the generator and "sends" a value that becomes
  183.                         the result of the current yield-expression
  184.         throw           used to raise an exception inside the generator'''
  185.     return isinstance(object, types.GeneratorType)
  186.  
  187.  
  188. def istraceback(object):
  189.     '''Return true if the object is a traceback.
  190.  
  191.     Traceback objects provide these attributes:
  192.         tb_frame        frame object at this level
  193.         tb_lasti        index of last attempted instruction in bytecode
  194.         tb_lineno       current line number in Python source code
  195.         tb_next         next inner traceback object (called by this level)'''
  196.     return isinstance(object, types.TracebackType)
  197.  
  198.  
  199. def isframe(object):
  200.     """Return true if the object is a frame object.
  201.  
  202.     Frame objects provide these attributes:
  203.         f_back          next outer frame object (this frame's caller)
  204.         f_builtins      built-in namespace seen by this frame
  205.         f_code          code object being executed in this frame
  206.         f_exc_traceback traceback if raised in this frame, or None
  207.         f_exc_type      exception type if raised in this frame, or None
  208.         f_exc_value     exception value if raised in this frame, or None
  209.         f_globals       global namespace seen by this frame
  210.         f_lasti         index of last attempted instruction in bytecode
  211.         f_lineno        current line number in Python source code
  212.         f_locals        local namespace seen by this frame
  213.         f_restricted    0 or 1 if frame is in restricted execution mode
  214.         f_trace         tracing function for this frame, or None"""
  215.     return isinstance(object, types.FrameType)
  216.  
  217.  
  218. def iscode(object):
  219.     '''Return true if the object is a code object.
  220.  
  221.     Code objects provide these attributes:
  222.         co_argcount     number of arguments (not including * or ** args)
  223.         co_code         string of raw compiled bytecode
  224.         co_consts       tuple of constants used in the bytecode
  225.         co_filename     name of file in which this code object was created
  226.         co_firstlineno  number of first line in Python source code
  227.         co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  228.         co_lnotab       encoded mapping of line numbers to bytecode indices
  229.         co_name         name with which this code object was defined
  230.         co_names        tuple of names of local variables
  231.         co_nlocals      number of local variables
  232.         co_stacksize    virtual machine stack space required
  233.         co_varnames     tuple of names of arguments and local variables'''
  234.     return isinstance(object, types.CodeType)
  235.  
  236.  
  237. def isbuiltin(object):
  238.     '''Return true if the object is a built-in function or method.
  239.  
  240.     Built-in functions and methods provide these attributes:
  241.         __doc__         documentation string
  242.         __name__        original name of this function or method
  243.         __self__        instance to which a method is bound, or None'''
  244.     return isinstance(object, types.BuiltinFunctionType)
  245.  
  246.  
  247. def isroutine(object):
  248.     '''Return true if the object is any kind of function or method.'''
  249.     if not isbuiltin(object) and isfunction(object) and ismethod(object):
  250.         pass
  251.     return ismethoddescriptor(object)
  252.  
  253.  
  254. def isabstract(object):
  255.     '''Return true if the object is an abstract base class (ABC).'''
  256.     if isinstance(object, type):
  257.         pass
  258.     return object.__flags__ & TPFLAGS_IS_ABSTRACT
  259.  
  260.  
  261. def getmembers(object, predicate = None):
  262.     '''Return all members of an object as (name, value) pairs sorted by name.
  263.     Optionally, only return members that satisfy a given predicate.'''
  264.     results = []
  265.     for key in dir(object):
  266.         value = getattr(object, key)
  267.         if not predicate or predicate(value):
  268.             results.append((key, value))
  269.             continue
  270.     
  271.     results.sort()
  272.     return results
  273.  
  274. Attribute = namedtuple('Attribute', 'name kind defining_class object')
  275.  
  276. def classify_class_attrs(cls):
  277.     """Return list of attribute-descriptor tuples.
  278.  
  279.     For each name in dir(cls), the return list contains a 4-tuple
  280.     with these elements:
  281.  
  282.         0. The name (a string).
  283.  
  284.         1. The kind of attribute this is, one of these strings:
  285.                'class method'    created via classmethod()
  286.                'static method'   created via staticmethod()
  287.                'property'        created via property()
  288.                'method'          any other flavor of method
  289.                'data'            not a method
  290.  
  291.         2. The class which defined this attribute (a class).
  292.  
  293.         3. The object as obtained directly from the defining class's
  294.            __dict__, not via getattr.  This is especially important for
  295.            data attributes:  C.data is just a data object, but
  296.            C.__dict__['data'] may be a data descriptor with additional
  297.            info, like a __doc__ string.
  298.     """
  299.     mro = getmro(cls)
  300.     names = dir(cls)
  301.     result = []
  302.     for name in names:
  303.         if name in cls.__dict__:
  304.             obj = cls.__dict__[name]
  305.         else:
  306.             obj = getattr(cls, name)
  307.         homecls = getattr(obj, '__objclass__', None)
  308.         if homecls is None:
  309.             for base in mro:
  310.                 if name in base.__dict__:
  311.                     homecls = base
  312.                     break
  313.                     continue
  314.             
  315.         
  316.         if homecls is not None and name in homecls.__dict__:
  317.             obj = homecls.__dict__[name]
  318.         
  319.         obj_via_getattr = getattr(cls, name)
  320.         if isinstance(obj, staticmethod):
  321.             kind = 'static method'
  322.         elif isinstance(obj, classmethod):
  323.             kind = 'class method'
  324.         elif isinstance(obj, property):
  325.             kind = 'property'
  326.         elif ismethod(obj_via_getattr) or ismethoddescriptor(obj_via_getattr):
  327.             kind = 'method'
  328.         else:
  329.             kind = 'data'
  330.         result.append(Attribute(name, kind, homecls, obj))
  331.     
  332.     return result
  333.  
  334.  
  335. def _searchbases(cls, accum):
  336.     if cls in accum:
  337.         return None
  338.     accum.append(cls)
  339.     for base in cls.__bases__:
  340.         _searchbases(base, accum)
  341.     
  342.  
  343.  
  344. def getmro(cls):
  345.     '''Return tuple of base classes (including cls) in method resolution order.'''
  346.     if hasattr(cls, '__mro__'):
  347.         return cls.__mro__
  348.     result = []
  349.     _searchbases(cls, result)
  350.     return tuple(result)
  351.  
  352.  
  353. def indentsize(line):
  354.     '''Return the indent size, in spaces, at the start of a line of text.'''
  355.     expline = string.expandtabs(line)
  356.     return len(expline) - len(string.lstrip(expline))
  357.  
  358.  
  359. def getdoc(object):
  360.     '''Get the documentation string for an object.
  361.  
  362.     All tabs are expanded to spaces.  To clean up docstrings that are
  363.     indented to line up with blocks of code, any whitespace than can be
  364.     uniformly removed from the second line onwards is removed.'''
  365.     
  366.     try:
  367.         doc = object.__doc__
  368.     except AttributeError:
  369.         return None
  370.  
  371.     if not isinstance(doc, types.StringTypes):
  372.         return None
  373.     return cleandoc(doc)
  374.  
  375.  
  376. def cleandoc(doc):
  377.     '''Clean up indentation from docstrings.
  378.  
  379.     Any whitespace that can be uniformly removed from the second line
  380.     onwards is removed.'''
  381.     
  382.     try:
  383.         lines = string.split(string.expandtabs(doc), '\n')
  384.     except UnicodeError:
  385.         return None
  386.  
  387.     margin = sys.maxint
  388.     for line in lines[1:]:
  389.         content = len(string.lstrip(line))
  390.         if content:
  391.             indent = len(line) - content
  392.             margin = min(margin, indent)
  393.             continue
  394.     
  395.     if lines:
  396.         lines[0] = lines[0].lstrip()
  397.     
  398.     if margin < sys.maxint:
  399.         for i in range(1, len(lines)):
  400.             lines[i] = lines[i][margin:]
  401.         
  402.     
  403.     while lines and not lines[-1]:
  404.         lines.pop()
  405.     while lines and not lines[0]:
  406.         lines.pop(0)
  407.     return string.join(lines, '\n')
  408.  
  409.  
  410. def getfile(object):
  411.     '''Work out which source or compiled file an object was defined in.'''
  412.     if ismodule(object):
  413.         if hasattr(object, '__file__'):
  414.             return object.__file__
  415.         raise TypeError('arg is a built-in module')
  416.     ismodule(object)
  417.     if isclass(object):
  418.         object = sys.modules.get(object.__module__)
  419.         if hasattr(object, '__file__'):
  420.             return object.__file__
  421.         raise TypeError('arg is a built-in class')
  422.     isclass(object)
  423.     if ismethod(object):
  424.         object = object.im_func
  425.     
  426.     if isfunction(object):
  427.         object = object.func_code
  428.     
  429.     if istraceback(object):
  430.         object = object.tb_frame
  431.     
  432.     if isframe(object):
  433.         object = object.f_code
  434.     
  435.     if iscode(object):
  436.         return object.co_filename
  437.     raise TypeError('arg is not a module, class, method, function, traceback, frame, or code object')
  438.  
  439. ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
  440.  
  441. def getmoduleinfo(path):
  442.     '''Get the module name, suffix, mode, and module type for a given file.'''
  443.     filename = os.path.basename(path)
  444.     suffixes = map((lambda info: (-len(info[0]), info[0], info[1], info[2])), imp.get_suffixes())
  445.     suffixes.sort()
  446.     for neglen, suffix, mode, mtype in suffixes:
  447.         if filename[neglen:] == suffix:
  448.             return ModuleInfo(filename[:neglen], suffix, mode, mtype)
  449.     
  450.  
  451.  
  452. def getmodulename(path):
  453.     '''Return the module name for a given file, or None.'''
  454.     info = getmoduleinfo(path)
  455.     if info:
  456.         return info[0]
  457.  
  458.  
  459. def getsourcefile(object):
  460.     '''Return the Python source file an object was defined in, if it exists.'''
  461.     filename = getfile(object)
  462.     if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
  463.         filename = filename[:-4] + '.py'
  464.     
  465.     for suffix, mode, kind in imp.get_suffixes():
  466.         if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
  467.             return None
  468.     
  469.     if os.path.exists(filename):
  470.         return filename
  471.     if hasattr(getmodule(object, filename), '__loader__'):
  472.         return filename
  473.  
  474.  
  475. def getabsfile(object, _filename = None):
  476.     '''Return an absolute path to the source or compiled file for an object.
  477.  
  478.     The idea is for each object to have a unique origin, so this routine
  479.     normalizes the result as much as possible.'''
  480.     if _filename is None:
  481.         if not getsourcefile(object):
  482.             pass
  483.         _filename = getfile(object)
  484.     
  485.     return os.path.normcase(os.path.abspath(_filename))
  486.  
  487. modulesbyfile = { }
  488. _filesbymodname = { }
  489.  
  490. def getmodule(object, _filename = None):
  491.     '''Return the module an object was defined in, or None if not found.'''
  492.     if ismodule(object):
  493.         return object
  494.     if hasattr(object, '__module__'):
  495.         return sys.modules.get(object.__module__)
  496.     if _filename is not None and _filename in modulesbyfile:
  497.         return sys.modules.get(modulesbyfile[_filename])
  498.     
  499.     try:
  500.         file = getabsfile(object, _filename)
  501.     except TypeError:
  502.         _filename in modulesbyfile
  503.         _filename in modulesbyfile
  504.         hasattr(object, '__module__')
  505.         return None
  506.         ismodule(object)
  507.  
  508.     if file in modulesbyfile:
  509.         return sys.modules.get(modulesbyfile[file])
  510.     for modname, module in sys.modules.items():
  511.         if ismodule(module) and hasattr(module, '__file__'):
  512.             f = module.__file__
  513.             _filesbymodname[modname] = f
  514.             f = getabsfile(module)
  515.             continue
  516.         modulesbyfile[f] = modulesbyfile[os.path.realpath(f)] = module.__name__
  517.     
  518.     if file in modulesbyfile:
  519.         return sys.modules.get(modulesbyfile[file])
  520.     main = sys.modules['__main__']
  521.     if not hasattr(object, '__name__'):
  522.         return None
  523.     builtin = sys.modules['__builtin__']
  524.  
  525.  
  526. def findsource(object):
  527.     '''Return the entire source file and starting line number for an object.
  528.  
  529.     The argument may be a module, class, method, function, traceback, frame,
  530.     or code object.  The source code is returned as a list of all the lines
  531.     in the file and the line number indexes a line in that list.  An IOError
  532.     is raised if the source code cannot be retrieved.'''
  533.     if not getsourcefile(object):
  534.         pass
  535.     file = getfile(object)
  536.     module = getmodule(object, file)
  537.     if module:
  538.         lines = linecache.getlines(file, module.__dict__)
  539.     else:
  540.         lines = linecache.getlines(file)
  541.     if not lines:
  542.         raise IOError('could not get source code')
  543.     lines
  544.     if ismodule(object):
  545.         return (lines, 0)
  546.     if isclass(object):
  547.         name = object.__name__
  548.         pat = re.compile('^(\\s*)class\\s*' + name + '\\b')
  549.         candidates = []
  550.         for i in range(len(lines)):
  551.             match = pat.match(lines[i])
  552.             if match:
  553.                 if lines[i][0] == 'c':
  554.                     return (lines, i)
  555.                 candidates.append((match.group(1), i))
  556.                 continue
  557.             lines[i][0] == 'c'
  558.         
  559.         if candidates:
  560.             candidates.sort()
  561.             return (lines, candidates[0][1])
  562.         raise IOError('could not find class definition')
  563.     isclass(object)
  564.     if ismethod(object):
  565.         object = object.im_func
  566.     
  567.     if isfunction(object):
  568.         object = object.func_code
  569.     
  570.     if istraceback(object):
  571.         object = object.tb_frame
  572.     
  573.     if isframe(object):
  574.         object = object.f_code
  575.     
  576.     if iscode(object):
  577.         if not hasattr(object, 'co_firstlineno'):
  578.             raise IOError('could not find function definition')
  579.         hasattr(object, 'co_firstlineno')
  580.         lnum = object.co_firstlineno - 1
  581.         pat = re.compile('^(\\s*def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)')
  582.         while lnum > 0:
  583.             if pat.match(lines[lnum]):
  584.                 break
  585.             
  586.             lnum = lnum - 1
  587.         return (lines, lnum)
  588.     raise IOError('could not find code object')
  589.  
  590.  
  591. def getcomments(object):
  592.     """Get lines of comments immediately preceding an object's source code.
  593.  
  594.     Returns None when source can't be found.
  595.     """
  596.     
  597.     try:
  598.         (lines, lnum) = findsource(object)
  599.     except (IOError, TypeError):
  600.         return None
  601.  
  602.     if ismodule(object):
  603.         start = 0
  604.         if lines and lines[0][:2] == '#!':
  605.             start = 1
  606.         
  607.         while start < len(lines) and string.strip(lines[start]) in ('', '#'):
  608.             start = start + 1
  609.         if start < len(lines) and lines[start][:1] == '#':
  610.             comments = []
  611.             end = start
  612.             while end < len(lines) and lines[end][:1] == '#':
  613.                 comments.append(string.expandtabs(lines[end]))
  614.                 end = end + 1
  615.             return string.join(comments, '')
  616.     elif lnum > 0:
  617.         indent = indentsize(lines[lnum])
  618.         end = lnum - 1
  619.         if end >= 0 and string.lstrip(lines[end])[:1] == '#' and indentsize(lines[end]) == indent:
  620.             comments = [
  621.                 string.lstrip(string.expandtabs(lines[end]))]
  622.             if end > 0:
  623.                 end = end - 1
  624.                 comment = string.lstrip(string.expandtabs(lines[end]))
  625.                 while comment[:1] == '#' and indentsize(lines[end]) == indent:
  626.                     comments[:0] = [
  627.                         comment]
  628.                     end = end - 1
  629.                     if end < 0:
  630.                         break
  631.                     
  632.                     comment = string.lstrip(string.expandtabs(lines[end]))
  633.             
  634.             while comments and string.strip(comments[0]) == '#':
  635.                 comments[:1] = []
  636.             while comments and string.strip(comments[-1]) == '#':
  637.                 comments[-1:] = []
  638.             return string.join(comments, '')
  639.     
  640.  
  641.  
  642. class EndOfBlock(Exception):
  643.     pass
  644.  
  645.  
  646. class BlockFinder:
  647.     '''Provide a tokeneater() method to detect the end of a code block.'''
  648.     
  649.     def __init__(self):
  650.         self.indent = 0
  651.         self.islambda = False
  652.         self.started = False
  653.         self.passline = False
  654.         self.last = 1
  655.  
  656.     
  657.     def tokeneater(self, type, token, srow_scol, erow_ecol, line):
  658.         (srow, scol) = srow_scol
  659.         (erow, ecol) = erow_ecol
  660.         if not self.started:
  661.             if token in ('def', 'class', 'lambda'):
  662.                 if token == 'lambda':
  663.                     self.islambda = True
  664.                 
  665.                 self.started = True
  666.             
  667.             self.passline = True
  668.         elif type == tokenize.NEWLINE:
  669.             self.passline = False
  670.             self.last = srow
  671.             if self.islambda:
  672.                 raise EndOfBlock
  673.             self.islambda
  674.         elif self.passline:
  675.             pass
  676.         elif type == tokenize.INDENT:
  677.             self.indent = self.indent + 1
  678.             self.passline = True
  679.         elif type == tokenize.DEDENT:
  680.             self.indent = self.indent - 1
  681.             if self.indent <= 0:
  682.                 raise EndOfBlock
  683.             self.indent <= 0
  684.         elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
  685.             raise EndOfBlock
  686.         
  687.  
  688.  
  689.  
  690. def getblock(lines):
  691.     '''Extract the block of code at the top of the given list of lines.'''
  692.     blockfinder = BlockFinder()
  693.     
  694.     try:
  695.         tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
  696.     except (EndOfBlock, IndentationError):
  697.         pass
  698.  
  699.     return lines[:blockfinder.last]
  700.  
  701.  
  702. def getsourcelines(object):
  703.     '''Return a list of source lines and starting line number for an object.
  704.  
  705.     The argument may be a module, class, method, function, traceback, frame,
  706.     or code object.  The source code is returned as a list of the lines
  707.     corresponding to the object and the line number indicates where in the
  708.     original source file the first line of code was found.  An IOError is
  709.     raised if the source code cannot be retrieved.'''
  710.     (lines, lnum) = findsource(object)
  711.     if ismodule(object):
  712.         return (lines, 0)
  713.     return (getblock(lines[lnum:]), lnum + 1)
  714.  
  715.  
  716. def getsource(object):
  717.     '''Return the text of the source code for an object.
  718.  
  719.     The argument may be a module, class, method, function, traceback, frame,
  720.     or code object.  The source code is returned as a single string.  An
  721.     IOError is raised if the source code cannot be retrieved.'''
  722.     (lines, lnum) = getsourcelines(object)
  723.     return string.join(lines, '')
  724.  
  725.  
  726. def walktree(classes, children, parent):
  727.     '''Recursive helper function for getclasstree().'''
  728.     results = []
  729.     classes.sort(key = attrgetter('__module__', '__name__'))
  730.     for c in classes:
  731.         results.append((c, c.__bases__))
  732.         if c in children:
  733.             results.append(walktree(children[c], children, c))
  734.             continue
  735.     
  736.     return results
  737.  
  738.  
  739. def getclasstree(classes, unique = 0):
  740.     """Arrange the given list of classes into a hierarchy of nested lists.
  741.  
  742.     Where a nested list appears, it contains classes derived from the class
  743.     whose entry immediately precedes the list.  Each entry is a 2-tuple
  744.     containing a class and a tuple of its base classes.  If the 'unique'
  745.     argument is true, exactly one entry appears in the returned structure
  746.     for each class in the given list.  Otherwise, classes using multiple
  747.     inheritance and their descendants will appear multiple times."""
  748.     children = { }
  749.     roots = []
  750.     for c in classes:
  751.         if c.__bases__:
  752.             for parent in c.__bases__:
  753.                 if parent not in children:
  754.                     children[parent] = []
  755.                 
  756.                 children[parent].append(c)
  757.                 if unique and parent in classes:
  758.                     break
  759.                     continue
  760.             
  761.         if c not in roots:
  762.             roots.append(c)
  763.             continue
  764.     
  765.     for parent in children:
  766.         if parent not in classes:
  767.             roots.append(parent)
  768.             continue
  769.     
  770.     return walktree(roots, children, None)
  771.  
  772. Arguments = namedtuple('Arguments', 'args varargs keywords')
  773.  
  774. def getargs(co):
  775.     """Get information about the arguments accepted by a code object.
  776.  
  777.     Three things are returned: (args, varargs, varkw), where 'args' is
  778.     a list of argument names (possibly containing nested lists), and
  779.     'varargs' and 'varkw' are the names of the * and ** arguments or None."""
  780.     if not iscode(co):
  781.         raise TypeError('arg is not a code object')
  782.     iscode(co)
  783.     nargs = co.co_argcount
  784.     names = co.co_varnames
  785.     args = list(names[:nargs])
  786.     step = 0
  787.     for i in range(nargs):
  788.         if args[i][:1] in ('', '.'):
  789.             stack = []
  790.             remain = []
  791.             count = []
  792.             while step < len(co.co_code):
  793.                 op = ord(co.co_code[step])
  794.                 step = step + 1
  795.                 if op >= dis.HAVE_ARGUMENT:
  796.                     opname = dis.opname[op]
  797.                     value = ord(co.co_code[step]) + ord(co.co_code[step + 1]) * 256
  798.                     step = step + 2
  799.                     if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
  800.                         remain.append(value)
  801.                         count.append(value)
  802.                     elif opname == 'STORE_FAST':
  803.                         stack.append(names[value])
  804.                         if not remain:
  805.                             stack[0] = [
  806.                                 stack[0]]
  807.                             break
  808.                         else:
  809.                             remain[-1] = remain[-1] - 1
  810.                             while remain[-1] == 0:
  811.                                 remain.pop()
  812.                                 size = count.pop()
  813.                                 stack[-size:] = [
  814.                                     stack[-size:]]
  815.                                 if not remain:
  816.                                     break
  817.                                 
  818.                                 remain[-1] = remain[-1] - 1
  819.                             if not remain:
  820.                                 break
  821.                             
  822.                     
  823.                 opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE')
  824.             args[i] = stack[0]
  825.             continue
  826.     
  827.     varargs = None
  828.     if co.co_flags & CO_VARARGS:
  829.         varargs = co.co_varnames[nargs]
  830.         nargs = nargs + 1
  831.     
  832.     varkw = None
  833.     if co.co_flags & CO_VARKEYWORDS:
  834.         varkw = co.co_varnames[nargs]
  835.     
  836.     return Arguments(args, varargs, varkw)
  837.  
  838. ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
  839.  
  840. def getargspec(func):
  841.     """Get the names and default values of a function's arguments.
  842.  
  843.     A tuple of four things is returned: (args, varargs, varkw, defaults).
  844.     'args' is a list of the argument names (it may contain nested lists).
  845.     'varargs' and 'varkw' are the names of the * and ** arguments or None.
  846.     'defaults' is an n-tuple of the default values of the last n arguments.
  847.     """
  848.     if ismethod(func):
  849.         func = func.im_func
  850.     
  851.     if not isfunction(func):
  852.         raise TypeError('arg is not a Python function')
  853.     isfunction(func)
  854.     (args, varargs, varkw) = getargs(func.func_code)
  855.     return ArgSpec(args, varargs, varkw, func.func_defaults)
  856.  
  857. ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
  858.  
  859. def getargvalues(frame):
  860.     """Get information about arguments passed into a particular frame.
  861.  
  862.     A tuple of four things is returned: (args, varargs, varkw, locals).
  863.     'args' is a list of the argument names (it may contain nested lists).
  864.     'varargs' and 'varkw' are the names of the * and ** arguments or None.
  865.     'locals' is the locals dictionary of the given frame."""
  866.     (args, varargs, varkw) = getargs(frame.f_code)
  867.     return ArgInfo(args, varargs, varkw, frame.f_locals)
  868.  
  869.  
  870. def joinseq(seq):
  871.     if len(seq) == 1:
  872.         return '(' + seq[0] + ',)'
  873.     return '(' + string.join(seq, ', ') + ')'
  874.  
  875.  
  876. def strseq(object, convert, join = joinseq):
  877.     '''Recursively walk a sequence, stringifying each element.'''
  878.     if type(object) in (list, tuple):
  879.         return join(map((lambda o, c = convert, j = join: strseq(o, c, j)), object))
  880.     return convert(object)
  881.  
  882.  
  883. def formatargspec(args, varargs = None, varkw = None, defaults = None, formatarg = str, formatvarargs = (lambda name: '*' + name), formatvarkw = (lambda name: '**' + name), formatvalue = (lambda value: '=' + repr(value)), join = joinseq):
  884.     '''Format an argument spec from the 4 values returned by getargspec.
  885.  
  886.     The first four arguments are (args, varargs, varkw, defaults).  The
  887.     other four arguments are the corresponding optional formatting functions
  888.     that are called to turn names and values into strings.  The ninth
  889.     argument is an optional function to format the sequence of arguments.'''
  890.     specs = []
  891.     if defaults:
  892.         firstdefault = len(args) - len(defaults)
  893.     
  894.     for i in range(len(args)):
  895.         spec = strseq(args[i], formatarg, join)
  896.         if defaults and i >= firstdefault:
  897.             spec = spec + formatvalue(defaults[i - firstdefault])
  898.         
  899.         specs.append(spec)
  900.     
  901.     if varargs is not None:
  902.         specs.append(formatvarargs(varargs))
  903.     
  904.     if varkw is not None:
  905.         specs.append(formatvarkw(varkw))
  906.     
  907.     return '(' + string.join(specs, ', ') + ')'
  908.  
  909.  
  910. def formatargvalues(args, varargs, varkw, locals, formatarg = str, formatvarargs = (lambda name: '*' + name), formatvarkw = (lambda name: '**' + name), formatvalue = (lambda value: '=' + repr(value)), join = joinseq):
  911.     '''Format an argument spec from the 4 values returned by getargvalues.
  912.  
  913.     The first four arguments are (args, varargs, varkw, locals).  The
  914.     next four arguments are the corresponding optional formatting functions
  915.     that are called to turn names and values into strings.  The ninth
  916.     argument is an optional function to format the sequence of arguments.'''
  917.     
  918.     def convert(name, locals = locals, formatarg = formatarg, formatvalue = formatvalue):
  919.         return formatarg(name) + formatvalue(locals[name])
  920.  
  921.     specs = []
  922.     for i in range(len(args)):
  923.         specs.append(strseq(args[i], convert, join))
  924.     
  925.     if varargs:
  926.         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  927.     
  928.     if varkw:
  929.         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  930.     
  931.     return '(' + string.join(specs, ', ') + ')'
  932.  
  933. Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
  934.  
  935. def getframeinfo(frame, context = 1):
  936.     '''Get information about a frame or traceback object.
  937.  
  938.     A tuple of five things is returned: the filename, the line number of
  939.     the current line, the function name, a list of lines of context from
  940.     the source code, and the index of the current line within that list.
  941.     The optional second argument specifies the number of lines of context
  942.     to return, which are centered around the current line.'''
  943.     if istraceback(frame):
  944.         lineno = frame.tb_lineno
  945.         frame = frame.tb_frame
  946.     else:
  947.         lineno = frame.f_lineno
  948.     if not isframe(frame):
  949.         raise TypeError('arg is not a frame or traceback object')
  950.     isframe(frame)
  951.     if not getsourcefile(frame):
  952.         pass
  953.     filename = getfile(frame)
  954.     if context > 0:
  955.         start = lineno - 1 - context // 2
  956.         
  957.         try:
  958.             (lines, lnum) = findsource(frame)
  959.         except IOError:
  960.             lines = None
  961.             index = None
  962.  
  963.         start = max(start, 1)
  964.         start = max(0, min(start, len(lines) - context))
  965.         lines = lines[start:start + context]
  966.         index = lineno - 1 - start
  967.     else:
  968.         lines = None
  969.         index = None
  970.     return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
  971.  
  972.  
  973. def getlineno(frame):
  974.     '''Get the line number from a frame object, allowing for optimization.'''
  975.     return frame.f_lineno
  976.  
  977.  
  978. def getouterframes(frame, context = 1):
  979.     '''Get a list of records for a frame and all higher (calling) frames.
  980.  
  981.     Each record contains a frame object, filename, line number, function
  982.     name, a list of lines of context, and index within the context.'''
  983.     framelist = []
  984.     while frame:
  985.         framelist.append((frame,) + getframeinfo(frame, context))
  986.         frame = frame.f_back
  987.     return framelist
  988.  
  989.  
  990. def getinnerframes(tb, context = 1):
  991.     """Get a list of records for a traceback's frame and all lower frames.
  992.  
  993.     Each record contains a frame object, filename, line number, function
  994.     name, a list of lines of context, and index within the context."""
  995.     framelist = []
  996.     while tb:
  997.         framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  998.         tb = tb.tb_next
  999.     return framelist
  1000.  
  1001. if hasattr(sys, '_getframe'):
  1002.     currentframe = sys._getframe
  1003. else:
  1004.     
  1005.     currentframe = lambda _ = None: pass
  1006.  
  1007. def stack(context = 1):
  1008.     """Return a list of records for the stack above the caller's frame."""
  1009.     return getouterframes(sys._getframe(1), context)
  1010.  
  1011.  
  1012. def trace(context = 1):
  1013.     '''Return a list of records for the stack below the current exception.'''
  1014.     return getinnerframes(sys.exc_info()[2], context)
  1015.  
  1016.